package Package.Example.CopyMultiLevelFolders;

import java.io.*;

public class CopyMultiLevelFolders {
    public static final void CopyMultiLevelFolders() throws IOException {
//   1. 创建数据源File对象，路径是E:\itcast
//2. 创建目的地File对象，路径是F:\
//3. 写方法实现文件夹的复制，参数为数据源File对象和目的地File对象
//4. 判断数据源File是否是文件
//是文件：直接复制，用字节流
//不是文件：
//在目的地下创建该目录
//遍历获取该目录下的所有文件的File数组，得到每一个File对象
//回到3继续(递归)
        File srcFile = new File("D:\\insert");
        File DestFile = new File("D:\\myCharStreams");
if (DestFile.exists()==false){
    DestFile.mkdir();

}
        copyFolder(srcFile, DestFile);
    }

    private static void copyFile(File srcFile, File destFile) throws IOException {
        BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile));
        System.out.println(destFile);
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(destFile));
        byte[] bys=new byte[1024];
        int len;
        while ((len=bis.read(bys))!=-1){
            bos.write(bys,0,len);
        }
        bos.close();
        bis.close();
    }

    private static void copyFolder(File srcFile, File destFile) throws IOException {
        if (srcFile.isDirectory()){
            String srcFileName=srcFile.getName();
            File newFolder=new File(destFile,srcFileName);
            if (!newFolder.exists()) {
                newFolder.mkdir();
            }
            File[] fileArray=srcFile.listFiles();
            for (File file:fileArray
                 ) {
                copyFolder(file,newFolder);
            }
        }else{
            File newFile=new File(destFile,srcFile.getName());
            copyFile(srcFile,newFile);
        }
    }
}
